package com.baozun.dev.payment.manager;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.baozun.dev.constant.PayMode;
import com.baozun.dev.data.AliPayData;
import com.baozun.dev.data.OrderInfo;
import com.baozun.dev.data.PayData;
import com.baozun.dev.payment.PaymentStrategy;
import com.baozun.dev.payment.alipay.AliPayPayment;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by joker.wang on 2017/8/16.
 */

public class BZPayManagers implements PayManagers {

    private OrderInfo orderInfo;

    private PayMode payMode;

    private Context mContext;

    private static final int REQUEST_SUCCESS_CODE = 200;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 200) {

                String response = (String) msg.obj;
                openPay(response);
            }
        }
    };

    public void startPayRequest() {
        new Thread(new HttpThread()).start();
    }


    /**
     * 调用BZPay接口
     */
    private class HttpThread extends Thread {
        @Override
        public void run() {
            try {
                URL postUrl = new URL("http://www.xxxxxxx.com");

                HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

                // http正文内，因此需要设为true
                connection.setDoOutput(true);
                // Read from the connection. Default is true.
                connection.setDoInput(true);
                connection.setRequestMethod("POST");
                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                connection.setUseCaches(false);
                //设置本次连接是否自动重定向
                connection.setInstanceFollowRedirects(true);
                // 配置本次连接的Content-type，配置为application/x-www-form-urlencoded的
                // 意思是正文是urlencoded编码过的form参数
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                // 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
                // 要注意的是connection.getOutputStream会隐含的进行connect。
                connection.connect();
                DataOutputStream out = new DataOutputStream(connection
                        .getOutputStream());
                // 正文，正文内容其实跟get的URL中 '? '后的参数字符串一致
                String content = "字段名=" + URLEncoder.encode("字符串值", "UTF-8");
                // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
                out.writeBytes(content);
                //流用完记得关
                out.flush();
                out.close();
                //获取响应
                if (connection.getResponseCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        line += line;
                    }
                    // 开启支付
                    Message message = handler.obtainMessage(REQUEST_SUCCESS_CODE);
                    message.obj = line;
                    handler.sendMessage(message);
                    reader.close();
                }
                //该干的都干完了,记得把连接断了
                connection.disconnect();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    /**
     * 开启支付
     *
     * @param responseStr
     */
    private void openPay(String responseStr) {

        PaymentStrategy paymentStrategy = new PaymentStrategy();
        if (payMode == PayMode.AlIPAY) {
            AliPayData aliPayData = (AliPayData) parseJson(responseStr);

            AliPayPayment aliPayPayment = new AliPayPayment(mContext, aliPayData);
            paymentStrategy.doPayment();

        } else if (payMode == PayMode.UNIONPAY) {


        } else if (payMode == PayMode.WECHATPAY) {

        }

    }

    /**
     * 解析数据
     *
     * @param json
     * @return
     */
    public PayData parseJson(String json) {
        AliPayData aliPayData = new AliPayData();
        return aliPayData;
    }


    public static class Builder {

        private BZPayManagers bzPayManagers;

        public Builder() {
            bzPayManagers = new BZPayManagers();
        }

        public Builder setPayMode(PayMode payMode) {
            bzPayManagers.payMode = payMode;
            return this;
        }

        public Builder setContext(Context mContext) {
            bzPayManagers.mContext = mContext;
            return this;
        }


        public Builder setorderInfo(OrderInfo orderInfo) {
            bzPayManagers.orderInfo = orderInfo;
            return this;
        }

        public BZPayManagers builder() {
            return bzPayManagers;
        }

    }


}
